//
//  IntroViewController.m
//  jingdongfang
//
//  Created by 郝志宇 on 16/8/2.
//  Copyright © 2016年 ZhiYu Hao. All rights reserved.
//

#import "IntroViewController.h"
#import "MingRenSlider.h"
#import "ZPViewController.h"
#import "JJViewController.h"
#import "GZViewController.h"
#import "FSViewController.h"
#import "IGShareModel.h"
#import "UIImage+MJ.h"
#import "YXScrollowActionSheet.h"
#import "TLChatViewController.h"
#import "IGIntroApi.h"
#import "IGArtGalleryAttentApi.h"
#import "IGUserInfo.h"
#import "IGMePubTopicVC.h"
#import "IGMyPictureListVC.h"

#define followBtnTag 494

@interface IntroViewController () <MingRenSliderVCDelegate> {
    UIImageView *background;
    UIImageView *icon;
    UILabel *name;
    
    MingRenSlider *slider;
    
    UIImageView *shadowImageView;
    NSInteger userSelectedChannelID;
    
    UIView *header;
    UIView *footer;
    
    ZPViewController *vc1;
    IGMyPictureListVC *vc2;
    IGMePubTopicVC *vc3;
    JJViewController *vc4;
    GZViewController *vc5;
    FSViewController *vc6;
    
    UIImage * _shareImage;
}
@property (nonatomic, strong) IGIntroApi *api;
@property (nonatomic, strong) NSMutableDictionary *dicData;
@property (nonatomic, strong) IGUserInfo *userInfo;
@property (nonatomic, strong) IGArtGalleryAttentApi *attentApi;
@end

@implementation IntroViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.isNavgationBarHidden = YES;
    if ([self respondsToSelector:@selector(setEdgesForExtendedLayout:)])
    {
        self.edgesForExtendedLayout = UIRectEdgeNone;
    }
    
    background = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, KSCREENWIDTH, INTROHEIGHT)];
    background.image = [UIImage imageNamed:@"个人主页bj1"];
    background.contentMode = UIViewContentModeScaleAspectFill;
    background.clipsToBounds = YES;
    [self.view addSubview:background];
    
    icon = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 70, 70)];
    icon.contentMode = UIViewContentModeScaleAspectFill;
    icon.layer.borderWidth = 1;
    icon.layer.borderColor = [UIColor whiteColor].CGColor;
    icon.layer.cornerRadius = icon.width/2;
    icon.layer.masksToBounds = YES;
    [background addSubview:icon];
    
    name = [[UILabel alloc] initWithFrame:CGRectZero];
    name.text = NSLocalizedString(@"User Nickname", nil);
    name.font = [UIFont boldSystemFontOfSize:17];
    name.textAlignment = NSTextAlignmentCenter;
    name.textColor = [UIColor whiteColor];
    [background addSubview:name];
    [name sizeToFit];
    
    icon.y = (background.height-icon.height-name.height-10)/2;
    icon.centerX = background.width/2;
    name.y = icon.bottom+10;
    name.centerX = background.width/2;
    
    UIButton *backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    backBtn.frame = CGRectMake(3, SafeTopMagin, 48, 48);
    [backBtn setImage:[UIImage imageNamed:@"A-sousuo-1"] forState:UIControlStateNormal];
    [backBtn setImageEdgeInsets:UIEdgeInsetsMake(2, 2, 2, 2)];
    [backBtn setTapActionWithBlock:^{
        [slider removeObserver:self forKeyPath:@"userSelectedChannelID"];
        [self.navigationController popViewControllerAnimated:YES];
    }];
    [self.view addSubview:backBtn];
    
    slider = [[MingRenSlider alloc] initWithFrame:CGRectMake(0, INTROHEIGHT, KSCREENWIDTH, KSCREENHEIGHT-49-INTROHEIGHT)];
    slider.slideSwitchViewDelegate = self;
    slider.tabItemNormalColor = [UIColor c5Color];
    slider.tabItemSelectedColor = [UIColor c4Color];
    
    [self.view addSubview:slider];
    
    [slider buildUI];
    
    [slider addObserver:self forKeyPath:@"userSelectedChannelID" options:NSKeyValueObservingOptionNew context:NULL];
    userSelectedChannelID = 100;
    header = [[UIView alloc] initWithFrame:CGRectMake(0, INTROHEIGHT, KSCREENWIDTH, 44)];
    shadowImageView = [[UIImageView alloc] init];
    shadowImageView.backgroundColor = slider.tabItemSelectedColor;
    [header addSubview:shadowImageView];
    
    NSArray *title = @[NSLocalizedString(@"Artworks", nil), @"画单", @"动态", NSLocalizedString(@"Intro", nil)];
    
    for (int i = 0; i < 4; i++)
    {
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        [button setFrame:CGRectMake(KSCREENWIDTH/4*i, 0, KSCREENWIDTH/4, 44)];
        
        //计算下一个tab的x偏移量
        [button setTag:i+100];
        if (i == 0) {
            shadowImageView.frame = CGRectMake(0, button.height-2, 60, 3);
            shadowImageView.centerX = button.centerX;
            shadowImageView.bottom = button.bottom;
            button.selected = YES;
        }
        [button setTitle:title[i] forState:UIControlStateNormal];
        button.titleLabel.font = [UIFont systemFontOfSize:15];
        [button setTitleColor:slider.tabItemNormalColor forState:UIControlStateNormal];
        [button setTitleColor:slider.tabItemSelectedColor forState:UIControlStateSelected];
        [button addTarget:self action:@selector(selectNameButton:) forControlEvents:UIControlEventTouchUpInside];
        [header addSubview:button];
    }
    header.backgroundColor = [UIColor whiteColor];
    
    [self.view addSubview:header];
    [self bottomButton];
    [self dataRequest];
}

- (void)creatShareBtn
{
    UIButton *share = [UIButton buttonWithType:UIButtonTypeCustom];
    share.frame = CGRectMake(0, SafeTopMagin, 48, 48);
    [share setImage:[UIImage imageNamed:@"A-fenxiang-1"] forState:UIControlStateNormal];
    [share setImageEdgeInsets:UIEdgeInsetsMake(2, 2, 2, 2)];
    __weak typeof(self) weakSelf = self;
    [share setTapActionWithBlock:^{
        IGShareModel *shareModel = [weakSelf.userInfo getShareModel];
        YXScrollowActionSheet *cusSheet = [[YXScrollowActionSheet alloc] init];
        cusSheet.shareModel = shareModel;
        [cusSheet show];
    }];
    [self.view addSubview:share];
    share.right=KSCREENWIDTH-3;
}

- (void)dataRequest
{
    self.dicData = [@{} mutableCopy];
    self.api = [IGIntroApi new];
    self.attentApi = [IGArtGalleryAttentApi new];
    self.api.aId = self.u_id;
    @KWeakObj(self)
    [self.api startWithDecodeClass:[IGIntroResp class] CompletionBlockWithSuccess:^(id responseObject, NSError *error) {
        if (responseObject)
        {
            IGIntroResp *resp = responseObject;
            IGIntroModel *model = resp.data;
            selfWeak.userInfo = model.member;
            [selfWeak upDataUI];
            [selfWeak creatShareBtn];
        }
    }];
}

- (void)setUserInfo:(IGUserInfo *)userInfo {
    if (_userInfo != userInfo) {
        _userInfo = userInfo;
        [self upDataUI];
    }
}

- (void)upDataUI
{
    UIButton *follow = [footer viewWithTag:followBtnTag];
    if ([_userInfo.attentionState isEqualToString:@"0"])
    { //是否 关注  0=已关注，1=未关注
        [follow setTitle:NSLocalizedString(@"Followed", nil) forState:UIControlStateNormal];
        [follow setTitleColor:[UIColor c4Color] forState:UIControlStateNormal];
    }
    else
    {
        [follow setTitle:[NSString stringWithFormat:@"+ %@",NSLocalizedString(@"Follow", nil)] forState:UIControlStateNormal];
        [follow setTitleColor:[UIColor appColor] forState:UIControlStateNormal];
    }
    
//    NSString *zpUnm = [NSString stringWithFormat:@"%@ %@", NSLocalizedString(@"Artworks", nil),_userInfo.worksNums?_userInfo.worksNums:@"0"];
//    NSString *gzUnm = [NSString stringWithFormat:@"%@ %@", NSLocalizedString(@"Follow", nil),_userInfo.focusNums?_userInfo.focusNums:@"0"];
//    NSString *fansUnm = [NSString stringWithFormat:@"%@ %@", NSLocalizedString(@"Fans", nil),_userInfo.followNums?_userInfo.followNums:@"0"];
//
//    for (UIView *sub in header.subviews)
//    {
//        if (sub.tag == 100)
//        { // 作品
//            [(UIButton *)sub setTitle:zpUnm forState:UIControlStateNormal];
//        }
//        else if (sub.tag == 101)
//        { // 简介
//            [(UIButton *)sub setTitle:NSLocalizedString(@"Intro", nil) forState:UIControlStateNormal];
//        }
//        else if (sub.tag == 102)
//        { // 关注
//            [(UIButton *)sub setTitle:gzUnm forState:UIControlStateNormal];
//        }
//        else if (sub.tag == 103)
//        { // 粉丝
//            [(UIButton *)sub setTitle:fansUnm forState:UIControlStateNormal];
//        }
//    }
    name.text = _userInfo.nike;
    [name sizeToFit];
    name.centerX = background.width/2;
    [icon sd_setImageWithURL:[NSURL URLWithString:_userInfo.image] placeholderImage:[UIImage imageNamed:@"place_head_Icon"]];
}

- (void)bottomButton
{
    NSArray *titleArr = @[NSLocalizedString(@"Follow", nil), NSLocalizedString(@"Private Message", nil)];
    NSArray *imgs = @[@"me-mail"];
    footer = [[UIView alloc] init];
    footer.backgroundColor = [UIColor c3Color];
    [self.view addSubview:footer];
    [footer mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.mas_equalTo(0);
        make.height.mas_equalTo(49);
    }];
    for (int i=0; i<2; i++) {
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        btn.titleLabel.font = [UIFont systemFontOfSize:15];
        btn.tag = followBtnTag+i;
        [btn setTitle:titleArr[i] forState:UIControlStateNormal];
        [btn setTitleColor:[UIColor c4Color] forState:UIControlStateNormal];
        [btn addTarget:self action:@selector(btnAction:) forControlEvents:UIControlEventTouchUpInside];
        [footer addSubview:btn];
        [btn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.bottom.mas_equalTo(0);
            make.left.mas_equalTo(KSCREENWIDTH/2*i);
            make.width.mas_equalTo(KSCREENWIDTH/2);
        }];
        if (i==0) {
            continue;
        }
        [btn setImage:[UIImage imageNamed:imgs[i-1]] forState:UIControlStateNormal];
        [btn setImageEdgeInsets:UIEdgeInsetsMake(0, -2, 0, 2)];
        [btn setTitleEdgeInsets:UIEdgeInsetsMake(0, 2, 0, -2)];
    }
    UILabel *line1 = [[UILabel alloc] init];
    line1.backgroundColor = [[UIColor c2Color] colorWithAlphaComponent:.5];
    [footer addSubview:line1];
    [line1 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(KSCREENWIDTH/2);
        make.top.mas_equalTo((49-28)/2);
        make.width.mas_equalTo(1.5
                               );
        make.height.mas_equalTo(28);
    }];

}

- (void)btnAction:(UIButton *)btn
{
    if (btn.tag-followBtnTag==0) {  // 关注
        if (_userInfo.attentionState) {
            if ([_userInfo.attentionState integerValue] == 0) { //是否 关注  0=已关注，1=未关注
                // 取消关注
                [self attentDataRequest:@"1"];
            } else { // 添加关注
                [self attentDataRequest:@"0"];
            }
        }
    } else if (btn.tag-followBtnTag==1) {  // 私信
        if ([_u_id isEqualToString:[IGUser getUid]]) {
            [self presentMessageTips:NSLocalizedString(@"Don't send private message to yourself.", nil)];
            return;
        }
        TLChatViewController *vc = [TLChatViewController new];
        vc.otherId = _u_id;
        vc.navigationItem.title = name.text;
        [UIViewController ig_pushViewController:vc animated:YES];
    }
}

- (void)attentDataRequest:(NSString *)operatorType
{
    self.attentApi.operatorType = operatorType;
    self.attentApi.museumId = _u_id;
    @KWeakObj(self)
    [self.attentApi startWithDecodeClass:[IGArtGalleryAttentResp class] CompletionBlockWithSuccess:^(id responseObject, NSError *error) {
        if (responseObject)
        {
            selfWeak.userInfo.attentionState = [selfWeak.userInfo.attentionState isEqualToString:@"0"]?@"1":@"0";
            [selfWeak dataRequest];
            [vc6 firstPage];
        }
    }];
}

#pragma mark - MingRenSliderVCDelegate
- (NSUInteger)numberOfTab:(MingRenSlider *)view
{
    return 4;
}

- (UIViewController *)slideSwitchView:(MingRenSlider *)view viewOfTab:(NSUInteger)number
{
    if (number == 0)
    {
        vc1 = [[ZPViewController alloc] init];
        vc1.u_id = _u_id;
        return vc1;
    }
    else if (number == 1)
    {
        vc2 = [[IGMyPictureListVC alloc] init];
        vc2.u_id = _u_id;
        return vc2;
    }
    else if (number == 2)
    {
        vc3 = [[IGMePubTopicVC alloc] init];
        vc3.pubUid = _u_id;
        return vc3;
    }
    else if (number == 3)
    {
        vc4 = [[JJViewController alloc] init];
        vc4.u_id = _u_id;
        return vc4;
    }
    else
    {
        UIViewController *vc = [[UIViewController alloc] init];
        return vc;
    }
}

- (void)selectNameButton:(UIButton *)sender
{
    //如果更换按钮
    if (sender.tag != userSelectedChannelID)
    {
        //取之前的按钮
        UIButton *lastButton = (UIButton *)[header viewWithTag:userSelectedChannelID];
        lastButton.selected = NO;
        //赋值按钮ID
        userSelectedChannelID = sender.tag;
    }
    //按钮选中状态
    if (!sender.selected)
    {
        //设置新页出现
        [slider selectNameButton:sender];
        sender.selected = YES;
        
        [UIView animateWithDuration:0.25 animations:^{
            shadowImageView.centerX = sender.centerX;
        }];
    }
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context
{
    if ([keyPath isEqualToString:@"userSelectedChannelID"])
    {
        NSNumber *new = [change objectForKey:@"new"];
        if ([new integerValue]!=userSelectedChannelID)
        {
            //取之前的按钮
            UIButton *lastButton = (UIButton *)[header viewWithTag:userSelectedChannelID];
            lastButton.selected = NO;
            //赋值按钮ID
            userSelectedChannelID = [new integerValue];
            UIButton *newButton = (UIButton *)[header viewWithTag:userSelectedChannelID];
            
            if (!newButton.selected)
            {
                newButton.selected = YES;
                [UIView animateWithDuration:0.25 animations:^{
                    shadowImageView.centerX = newButton.centerX;
                }];
            }
        }
    }
}

@end
